package org.example.testcode.controller;

import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import org.example.testcode.bean.TopicEsInfo;
import org.example.testcode.helper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;


@RequestMapping("/admin")
@RestController
public class TopicAdminController {


    @Autowired
    EsTemplate esTemplate;

    public static final String topicIndex = "techtopic";
    public static final String DomainAccessKey = "www.guoxiongfei.cn";

    /**
     * 拉取cnblog
     *
     * @param domain
     * @return
     * @throws Exception
     */
    @GetMapping("/testget")
    public String testGet(String domain) throws Exception {
        if (null == domain || !DomainAccessKey.equals(domain)) {
            return null;
        }
        //esTemplate.createIndex(topicIndex);
        List<String> allAuthorRss = TopicHelper.allAuthorRss();
        List<TopicEsInfo> infoList = new ArrayList<>(); // TopicHelper.getTopicByAuthorRss(allAuthorRss.get(1));
        /*for (String link : allAuthorRss) {
            //infoList.addAll(TopicHelper.getTopicByAuthorRss(link));

            infoList = TopicHelper.getTopicByAuthorRss(link);
            esTemplate.bulkAdd(topicIndex, TopicEsInfo.class.getTypeName(), infoList);
            System.out.println("insert success infoList:" + infoList.size());
        }*/
        //allAuthorRss = new ArrayList<>();
        esTemplate.createIndex(topicIndex);
        for (int i = 0; i < allAuthorRss.size(); i++) {
            //infoList.addAll(TopicHelper.getTopicByAuthorRss(link));
            infoList = TopicHelper.getTopicByAuthorRss(allAuthorRss.get(i));
            if (infoList.size() < 1) {
                continue;
            }
            //esTemplate.bulkAdd(topicIndex, TopicEsInfo.class.getTypeName(), infoList);
            esTemplate.bulkAdd(topicIndex, infoList);
            System.out.println("【" + i + "/" + allAuthorRss.size() + "】insert success infoList:" + infoList.size());
        }
        System.out.println("done");
        //esTemplate.createIndex(topicIndex);

        //esTemplate.bulkAdd(topicIndex, TopicEsInfo.class.getTypeName(), infoList);

        return null;

    }

    @GetMapping("/add")
    public void main(String domain) throws IOException {
        if (null == domain || !DomainAccessKey.equals(domain)) {
            return;
        }

        List<TopicEsInfo> infoList = new ArrayList<>();
        TopicEsInfo info = new TopicEsInfo();
        boolean b = esTemplate.checkIndexExists(topicIndex);
        if (!b) {
            //esTemplate.deleteIndex(topicIndex);
            esTemplate.createIndex(topicIndex);
        }

        {

            info.setTitle("统统特价甩卖只要1元，只要9.9包邮");
            info.setNavText("");
            info.setLink("/item/29046");
            info.setDocId(MD5Helper.GetTopicUnionId(info.getLink()));
            infoList.clear();
            infoList.add(info);
            //esTemplate.bulkAdd(topicIndex, TopicEsInfo.class.getTypeName(), infoList);
            esTemplate.bulkAdd(topicIndex, infoList);
        }

        {

            info.setTitle("统统特价甩卖只要1元");
            info.setNavText("全部只要9.9包邮");
            info.setLink("/item/29046");
            info.setDocId(MD5Helper.GetTopicUnionId(info.getLink()));
            infoList.clear();
            infoList.add(info);
            //esTemplate.bulkAdd(topicIndex, TopicEsInfo.class.getTypeName(), infoList);
            esTemplate.bulkAdd(topicIndex, infoList);
        }


        {
            info.setTitle("统统特价甩卖只要1元");
            info.setBodyText("商城清货，清库存，只要9.9包邮");
            info.setLink("/item/29047");
            info.setDocId(MD5Helper.GetTopicUnionId(info.getLink()));
            infoList.clear();
            infoList.add(info);
            //esTemplate.bulkAdd(topicIndex, TopicEsInfo.class.getTypeName(), infoList);
            esTemplate.bulkAdd(topicIndex, infoList);
        }


    }

    /**
     * 后台编辑话题
     *
     * @param keywords
     * @param pageNo
     * @param pageSize
     * @param domain
     * @return
     */
    @GetMapping("/edit")
    public String editHits(String keywords, Long pageNo, Long pageSize, String domain) throws IOException {
        if (null == domain || !DomainAccessKey.equals(domain)) {
            return null;
        }
        if (null == pageNo) {
            pageNo = 1L;
        }
        if (null == pageSize) {
            pageSize = 10L;
        }
        if (!(null != keywords && keywords.length() > 0)) {
            keywords = "好好学习，天天向上";
        }
        if (keywords.length() > 30) {
            keywords = keywords.substring(0, 29);
        }
        PageResult<TopicEsInfo> object = esTemplate.searchTopic(topicIndex, "*", null, pageNo.intValue(), pageSize.intValue());
        if (null != object && null != object.getResult() && object.getResult().size() > 0) {
            List<TopicEsInfo> updateList = new ArrayList<>();
            for (TopicEsInfo es : object.getResult()) {
                if (null != es.getBodyText() && es.getBodyText().length() > 0) {
                    continue;
                }
                TopicEsInfo cnBlogByLink = TopicHelper.getCNBlogByLink(es.getLink());
                if (null == cnBlogByLink) {
                    System.out.println("获取内容失败：" + es.getLink());
                    continue;
                }
                es.setBodyText(cnBlogByLink.getBodyText());
                if (null != cnBlogByLink.getBodyText() && cnBlogByLink.getBodyText().length() > 0) {
                    es.setNavText(getNavTxt(cnBlogByLink.getBodyText()));
                }
                es.setPicUrl(cnBlogByLink.getPicUrl());
                es.setPicUrl2(cnBlogByLink.getPicUrl2());

                updateList.add(es);
            }
            if (updateList.size() > 0) {
                esTemplate.bulkAdd(topicIndex, TopicEsInfo.class.getTypeName(), updateList);
            }
        }


        //return JSON.toJSONString(object);
        return String.format("fn_topic_page(%s)", JSON.toJSONString(object));
    }


    @GetMapping("/batchUpdate")
    public void batchUpdate(String domain) throws IOException {
        if (null == domain || !DomainAccessKey.equals(domain)) {
            return;
        }
        Long pageNo = 1L;
        Long pageSize = 1L;

        PageResult<TopicEsInfo> object = esTemplate.searchTopic(topicIndex, "*", null, pageNo.intValue(), pageSize.intValue());
        int totalPage = 1;
        if (null != object) {
            totalPage = (object.getRecordCount() == 0 ? 10 : object.getRecordCount()) / 10 + 1;
            updateList(object);
            System.out.println("处理完【1" + (totalPage + 1) + "】");
            for (int p = 2; p < totalPage + 1; p++) {
                object = esTemplate.searchTopic(topicIndex, "*", null, p, pageSize.intValue());
                updateList(object);
                System.out.println("处理完【" + p + "/" + (totalPage + 1) + "】");
            }
        }

    }

    private void updateList(PageResult<TopicEsInfo> object) throws IOException {
        if (null != object && null != object.getResult() && object.getResult().size() > 0) {
            List<TopicEsInfo> updateList = new ArrayList<>();
            for (TopicEsInfo es : object.getResult()) {
                if (null != es.getBodyText() && es.getBodyText().length() > 0) {
                    continue;
                }
                TopicEsInfo cnBlogByLink = TopicHelper.getCNBlogByLink(es.getLink());
                if (null == cnBlogByLink) {
                    System.out.println("获取内容失败：" + es.getLink());
                    continue;
                }
                es.setBodyText(cnBlogByLink.getBodyText());
                if (null != cnBlogByLink.getBodyText() && cnBlogByLink.getBodyText().length() > 0) {
                    es.setNavText(getNavTxt(cnBlogByLink.getBodyText()));
                }
                es.setPicUrl(cnBlogByLink.getPicUrl());
                es.setPicUrl2(cnBlogByLink.getPicUrl2());

                updateList.add(es);
            }
            if (updateList.size() > 0) {
                esTemplate.bulkAdd(topicIndex, TopicEsInfo.class.getTypeName(), updateList);
            }
        }
    }


    private String getNavTxt(String bodyText) {
        String navTxt = bodyText.replace(" ", "").replace("\r", "").replace("\n", "");
        if (navTxt.length() > 200) {
            navTxt = navTxt.substring(0, 200);
        }
        return navTxt;
    }


    @GetMapping("/backup")
    public String backup() {
        PageResult<TopicEsInfo> oldPage = esTemplate.searchTopic(topicIndex, "", null, 1, 10);
        int pageSize = 10;
        int pageCount = (oldPage.getRecordCount() + pageSize - 1) / pageSize;
        ExecutorService executorService = ThreadPoolHelper.getFixedThreadPool((int) pageCount, "back_es");
        List<Future> futureList = new ArrayList<>();
        for (int i = 0; i < pageCount; i++) {
            Future f = executorService.submit(new EsBackupTask(i + 1, pageSize, null));
            futureList.add(f);
        }
        executorService.shutdown();
        futureList.forEach(i -> {
            try {
                Object o = i.get();
                System.out.println("[" + o + "/" + pageCount + "]success");
            } catch (Exception e) {
                System.out.println("future get error:" + e.getMessage());
                throw new RuntimeException(e);
            }
        });

        return null;
    }

    public class EsBackupTask implements Callable<String> {

        private int pageIndex;
        private int pageSize;
        private Object source;

        public EsBackupTask(int pageIndex, int pageSize, Object source) {
            this.pageIndex = pageIndex;
            this.pageSize = pageSize;
            this.source = source;
        }

        @SneakyThrows
        //@Override
        public void run() {
            System.out.println(this.pageIndex + " run()");
            PageResult<TopicEsInfo> oldPage = esTemplate.searchTopic(topicIndex, "", null, pageIndex, pageSize);
            System.out.println(this.pageIndex + ",pageSize:" + oldPage.getResult().size());
            if (null != oldPage.getResult() && oldPage.getResult().size() > 0) {
                esTemplate.bulkAddByRemote(EsTemplate.topicIndex, oldPage.getResult());
                TimeUnit.SECONDS.sleep(1);
            }
        }

        @Override
        public String call() throws Exception {
            PageResult<TopicEsInfo> oldPage = esTemplate.searchTopic(topicIndex, "", null, pageIndex, pageSize);
            System.out.println(this.pageIndex + ",pageSize:" + oldPage.getResult().size());
            if (null != oldPage.getResult() && oldPage.getResult().size() > 0) {
                esTemplate.bulkAddByRemote(EsTemplate.topicIndex, oldPage.getResult());
            }
            return this.pageIndex + "";
        }
    }


    /**
     * 前端按关键词搜索
     *
     * @param keywords
     * @param pageNo
     * @param pageSize
     * @param domain
     * @return
     */
    @GetMapping("/s")
    public String searchHits(String keywords, String sort, Long pageNo, Long pageSize, String domain) {
        if (null == domain || !DomainAccessKey.equals(domain)) {
            return null;
        }
        if (null == pageNo) {
            pageNo = 1L;
        }
        if (null == pageSize) {
            pageSize = 10L;
        }
        if (!(null != keywords && keywords.length() > 0)) {
            keywords = "";
            //keywords = "好好学习，天天向上";
        }
        if (keywords.length() > 30) {
            keywords = keywords.substring(0, 29);
        }
        PageResult<TopicEsInfo> object = esTemplate.searchTopic(topicIndex, keywords, sort, pageNo.intValue(), pageSize.intValue());

        //return JSON.toJSONString(object);
        return String.format("fn_topic_page(%s)", JSON.toJSONString(object));
    }

    /**
     * 前端按ID查询
     *
     * @param id
     * @return
     * @throws IOException
     */
    @GetMapping("/get")
    public String getById(String id) throws IOException {
        if (!(null != id && id.length() > 0)) {
            return null;
        }
        Object object = esTemplate.getDocument(topicIndex, TopicEsInfo.class.getTypeName(), id);
        TopicEsInfo es = JSON.parseObject(JSON.toJSONString(object), TopicEsInfo.class);
        {
            if (null != es.getBodyText() && es.getBodyText().length() > 0) {

            } else {
                TopicEsInfo cnBlogByLink = TopicHelper.getCNBlogByLink(es.getLink());
                if (null == cnBlogByLink) {
                    System.out.println("获取内容失败：" + es.getLink());

                } else {
                    es.setBodyText(cnBlogByLink.getBodyText());
                    if (null != cnBlogByLink.getBodyText() && cnBlogByLink.getBodyText().length() > 0) {
                        es.setNavText(getNavTxt(cnBlogByLink.getBodyText()));
                    }
                    es.setPicUrl(cnBlogByLink.getPicUrl());
                    es.setPicUrl2(cnBlogByLink.getPicUrl2());

                    List<TopicEsInfo> updateList = new ArrayList<>();
                    updateList.add(es);
                    esTemplate.bulkAdd(topicIndex, TopicEsInfo.class.getTypeName(), updateList);

                }
            }
        }
        return String.format("fn_topic(%s)", JSON.toJSONString(object));
    }

}
